#include"Queue.h"

typedef int QDataType;
typedef struct QueueNode
{
	struct QueueNode* next;
	QDataType data;
}QNode;

typedef struct Queue
{
	QNode* phead;
	QNode* ptail;
	int size;
}Queue;

void QueueInit(Queue* pq)
{
    assert(pq);

    pq->phead = NULL;
    pq->ptail = NULL;
    pq->size = 0;
};
void QueueDestroy(Queue* pq)
{
    assert(pq);

    QNode* cur = pq->phead;
    while(cur)
    {
        QNode* next = cur->next;
        free(cur);
        cur = next;
    }

    pq->phead = pq->ptail = NULL;
    pq->size = 0;
};

void QueuePush(Queue* pq, QDataType x)
{
    assert(pq);

    QNode* newnode = (QNode*)malloc(sizeof(QNode));
    if(newnode == NULL)
    {
        perror("malloc fail!\n");
        return;
    }
    newnode->data = x;
    newnode->next = NULL;

    if(pq->ptail = NULL)
    {
        assert(pq->phead = NULL);

        pq->phead = pq->ptail = newnode;
    } 
    else
    {
        pq->ptail->next = newnode;
        pq->ptail = newnode;
    }

    pq->size++;
};

bool QueueEmpty(Queue* pq)
{
    assert(pq);

    return pq->size == 0;
};
void QueuePop(Queue* pq)
{
    assert(pq);                     //判断是否是空指针
    assert(!QueueEmpty(pq));        //判断是否是空队列

    if(pq->phead->next == NULL)
    {
        free(pq->phead);
        pq->phead = pq->ptail = NULL;
    }
    else
    {
        QNode* next = pq->phead->next;
        free(pq->phead);
        pq->phead = next;
    }

    pq->size--;
};

QDataType QueueFront(Queue* pq)   //获取头部元素
{
    assert(pq);                     //判断是否是空指针
    assert(!QueueEmpty(pq));        //判断是否是空队列

    return pq->phead->data;
};
QDataType QueueBack(Queue* pq)    //获取尾部元素
{
    assert(pq);                     //判断是否是空指针
    assert(!QueueEmpty(pq));        //判断是否是空队列

    return pq->ptail->data;
};
int QueueSize(Queue* pq)
{
    assert(pq);

    return pq->size;
};
